<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>06-Promise的链式调用</title>
  
    
      <meta 
        property="og:title" 
        content="06-Promise的链式调用">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/06-Promise%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2006-06-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础异步">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%A4%84%E7%90%86%E5%A4%9A%E6%AC%A1-Ajax-%E8%AF%B7%E6%B1%82%E3%80%90%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">Promise 的链式调用：处理多次 Ajax 请求【重要】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#ES5-%E4%B8%AD%E7%9A%84%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">ES5 中的传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%88%9D%E6%AD%A5%E5%86%99%E6%B3%95%EF%BC%8C%E6%96%B9%E4%BE%BF%E7%90%86%E8%A7%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（初步写法，方便理解）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装一个接口）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装多个接口）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%B0%81%E8%A3%85-Node-js-%E7%9A%84%E5%9B%9E%E8%B0%83%E6%96%B9%E6%B3%95"><span class="toc-text">Promise 链式调用：封装 Node.js 的回调方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%8C%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81"><span class="toc-text">链式调用，如何处理 reject 失败状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-1%EF%BC%9A%E4%B8%8D%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 1：不处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-2%EF%BC%9A%E5%8D%95%E7%8B%AC%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 2：单独处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9F%E4%B8%80%E5%A4%84%E7%90%86-reject"><span class="toc-text">统一处理 reject</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#return-%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-text">return 的返回值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-1%EF%BC%9A%E8%BF%94%E5%9B%9E-Promise-%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1"><span class="toc-text">情况 1：返回 Promise 实例对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-2%EF%BC%9A%E8%BF%94%E5%9B%9E-%E6%99%AE%E9%80%9A%E5%80%BC"><span class="toc-text">情况 2：返回 普通值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      06-Promise的链式调用
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2006-05-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2006-06-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
          class="post-meta-link">
          JS基础异步
        </a>
      
    
    
      <span class="dot"></span>
      <span>3k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
            class="post-meta-link">
            JS基础异步
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="Promise-的链式调用：处理多次-Ajax-请求【重要】"><a href="#Promise-的链式调用：处理多次-Ajax-请求【重要】" class="headerlink" title="Promise 的链式调用：处理多次 Ajax 请求【重要】"></a>Promise 的链式调用：处理多次 Ajax 请求【重要】</h2><p>实际开发中，我们经常需要同时请求多个接口。比如说：在请求完<code>接口1</code>的数据<code>data1</code>之后，需要根据<code>data1</code>的数据，继续请求接口 2，获取<code>data2</code>；然后根据<code>data2</code>的数据，继续请求接口 3。</p>
<p>换而言之，现在有三个网络请求，请求 2 必须依赖请求 1 的结果，请求 3 必须依赖请求 2 的结果，如果按照往常的写法，会有三层回调，会陷入“回调地狱”。</p>
<p>这种场景其实就是接口的多层嵌套调用。有了 Promise 之后，我们可以把多层嵌套调用按照<strong>线性</strong>的方式进行书写，非常优雅。也就是说：Promise 可以把原本的<strong>多层嵌套写法</strong>改进为<strong>链式写法</strong>。</p>
<h3 id="ES5-中的传统写法"><a href="#ES5-中的传统写法" class="headerlink" title="ES5 中的传统写法"></a>ES5 中的传统写法</h3><pre class="highlight"><span class="line"><span class="comment">// 封装 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 执行 ajax 请求</span></span><br><span class="line"><span class="title function_">ajax</span>(</span><br><span class="line">    <span class="string">&#x27;/a.json&#x27;</span>,</span><br><span class="line">    <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 第一个接口请求成功:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(res));</span><br><span class="line">        <span class="comment">// ajax嵌套调用</span></span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;b.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 第二个接口请求成功:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(res));</span><br><span class="line">            <span class="comment">// ajax嵌套调用</span></span><br><span class="line">            <span class="title function_">ajax</span>(<span class="string">&#x27;c.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 第三个接口请求成功:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(res));</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao 请求失败:&#x27;</span> + <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(err));</span><br><span class="line">    &#125;</span><br><span class="line">);</span><br></pre>

<p>上面的代码层层嵌套，可读性很差，而且出现了我们常说的回调地狱问题。</p>
<h3 id="Promise-链式调用（初步写法，方便理解）"><a href="#Promise-链式调用（初步写法，方便理解）" class="headerlink" title="Promise 链式调用（初步写法，方便理解）"></a>Promise 链式调用（初步写法，方便理解）</h3><p>如果我们不对 Promise 的链式调用进行封装，那么，它的简单写法是下面这样的：</p>
<pre class="highlight"><span class="line"><span class="comment">// 封装 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">ajax</span>(<span class="string">&#x27;a.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="title function_">resolve</span>();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;a成功&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">ajax</span>(<span class="string">&#x27;b.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">                <span class="title function_">resolve</span>();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;b成功&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">ajax</span>(<span class="string">&#x27;c.json&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">                <span class="title function_">resolve</span>();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        cnosole.<span class="title function_">log</span>(<span class="string">&#x27;c成功&#x27;</span>);</span><br><span class="line">    &#125;);</span><br></pre>

<p>上面代码中，then 是可以链式调用的，一旦 return 一个新的 promise 实例之后，后面的 then 就可以拿到前面 resolve 出来的数据。这种<strong>扁平化</strong>的写法，更方便维护；并且可以更好的<strong>管理</strong>请求成功和失败的状态。</p>
<p>但是，你可能会奇怪，上面的代码，怎么这么多？而且有不少重复。因为这里只是采用了一种笨拙的方式来写，为的是方便大家理解 promise 的执行过程。我们其实可以对 promise 的链式调用进行封装。</p>
<p>怎么个封装法呢？上面的代码中，每次在 return 一个 promise 的时候，只是 url 地址不一样，其他的代码是一样的。所以我们可以把重复的代码封装成函数。写法如下。</p>
<h3 id="Promise-链式调用（封装一个接口）"><a href="#Promise-链式调用（封装一个接口）" class="headerlink" title="Promise 链式调用（封装一个接口）"></a>Promise 链式调用（封装一个接口）</h3><p>针对同一个接口的多次嵌套调用，采用 promise 封装后的写法如下：</p>
<pre class="highlight"><span class="line"><span class="comment">// 定义 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一步：model层，接口封装</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getPromise</span>(<span class="params">url</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">ajax</span>(url, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 这里的 res 是接口的返回结果。返回码 retCode 是动态数据。</span></span><br><span class="line">            <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// 接口请求成功时调用</span></span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&#x27;request success&#x27;</span> + res);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 接口请求异常时调用</span></span><br><span class="line">                <span class="title function_">reject</span>(&#123; <span class="attr">retCode</span>: -<span class="number">1</span>, <span class="attr">msg</span>: <span class="string">&#x27;network error&#x27;</span> &#125;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二步：业务层的接口调用。这里的 data 就是 从 resolve 和 reject 传过来的，也就是从接口拿到的数据</span></span><br><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// a 请求成功。从 resolve 获取正常结果：接口请求成功后，打印a接口的返回结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;b.json&#x27;</span>); <span class="comment">// 继续请求 b</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// b 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;c.json&#x27;</span>); <span class="comment">// 继续请求 c</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// c 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 reject中获取异常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(e);</span><br><span class="line">    &#125;);</span><br></pre>

<p>怎么样？上面代码是不是非常简洁？而且可读性很强。</p>
<p>代码写到这里，我们还可以再继续优化一下。细心的你可以发现，我们在做三次嵌套请求的时候，针对 resolve 和 reject 的处理时机是一样的。如果你的业务是针对<strong>同一个接口</strong>连续做了三次调用，只是请求<strong>传参不同</strong>，那么，按上面这样写是没有问题的。</p>
<p>但是，真正在实战中，我们往往需要嵌套请求<strong>多个不同的接口</strong>，要处理的 resolve 和 reject 的时机和逻辑往往是不同的，所以需要分开封装不同的 Promise 实例，这在实战开发中更为常见。代码应该是像下面这样写。</p>
<h3 id="Promise-链式调用（封装多个接口）"><a href="#Promise-链式调用（封装多个接口）" class="headerlink" title="Promise 链式调用（封装多个接口）"></a>Promise 链式调用（封装多个接口）</h3><p>针对多个不同接口的嵌套调用，采用 promise 封装后的写法如下：</p>
<pre class="highlight"><span class="line"><span class="comment">// 封装 ajax 请求：传入回调函数 success 和 fail</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">ajax</span>(<span class="params">url, success, fail</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> xmlhttp = <span class="keyword">new</span> <span class="title class_">XMLHttpRequest</span>();</span><br><span class="line">    xmlhttp.<span class="title function_">open</span>(<span class="string">&#x27;GET&#x27;</span>, url);</span><br><span class="line">    xmlhttp.<span class="title function_">send</span>();</span><br><span class="line">    xmlhttp.<span class="property">onreadystatechange</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xmlhttp.<span class="property">readyState</span> === <span class="number">4</span> &amp;&amp; xmlhttp.<span class="property">status</span> === <span class="number">200</span>) &#123;</span><br><span class="line">            success &amp;&amp; <span class="title function_">success</span>(xmlhttp.<span class="property">responseText</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            fail &amp;&amp; <span class="title function_">fail</span>(<span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&#x27;接口请求失败&#x27;</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Promise 封装接口1</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request1</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;https://www.baidu.com&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">201</span>) &#123;</span><br><span class="line">                <span class="comment">// 接口请求成功时调用：这里的 res 是接口1的返回结果</span></span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&#x27;request1 success&#x27;</span> + res);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 接口请求异常时调用异常</span></span><br><span class="line">                <span class="title function_">reject</span>(<span class="string">&#x27;接口1请求失败&#x27;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Promise 封装接口2</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request2</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;https://www.jd.com&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">202</span>) &#123;</span><br><span class="line">                <span class="comment">// 这里的 res 是接口2的返回结果</span></span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&#x27;request2 success&#x27;</span> + res);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="title function_">reject</span>(<span class="string">&#x27;接口2请求失败&#x27;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Promise 封装接口3</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request3</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="title function_">ajax</span>(<span class="string">&#x27;https://www.taobao.com&#x27;</span>, <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (res.<span class="property">retCode</span> == <span class="number">203</span>) &#123;</span><br><span class="line">                <span class="comment">// 这里的 res 是接口3的返回结果</span></span><br><span class="line">                <span class="title function_">resolve</span>(<span class="string">&#x27;request3 success&#x27;</span> + res);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="title function_">reject</span>(<span class="string">&#x27;接口3请求失败&#x27;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 先发起request1，等resolve后再发起request2；紧接着，等 request2有了 resolve之后，再发起 request3</span></span><br><span class="line"><span class="title function_">request1</span>()</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res1</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 接口1请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res1);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">request2</span>();</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res2</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 接口2请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res2);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">request3</span>();</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res3</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 接口3请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res3);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 从 reject中获取异常结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;);</span><br></pre>

<p>这段代码很经典，你一定要多看几遍，多默写几遍。倒背如流也不过分。</p>
<h2 id="Promise-链式调用：封装-Node-js-的回调方法"><a href="#Promise-链式调用：封装-Node-js-的回调方法" class="headerlink" title="Promise 链式调用：封装 Node.js 的回调方法"></a>Promise 链式调用：封装 Node.js 的回调方法</h2><h3 id="传统写法"><a href="#传统写法" class="headerlink" title="传统写法"></a>传统写法</h3><pre class="highlight"><span class="line">fs.<span class="title function_">readFile</span>(A, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">    fs.<span class="title function_">readFile</span>(B, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">        fs.<span class="title function_">readFile</span>(C, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">            fs.<span class="title function_">readFile</span>(D, <span class="string">&#x27;utf-8&#x27;</span>, <span class="keyword">function</span> (<span class="params">err, data</span>) &#123;</span><br><span class="line">                <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao:&#x27;</span> + data);</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre>

<p>上方代码多层嵌套，存在回调地狱的问题。</p>
<h3 id="Promise-写法"><a href="#Promise-写法" class="headerlink" title="Promise 写法"></a>Promise 写法</h3><pre class="highlight"><span class="line"><span class="keyword">function</span> <span class="title function_">read</span>(<span class="params">url</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        fs.<span class="title function_">readFile</span>(url, <span class="string">&#x27;utf8&#x27;</span>, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) <span class="title function_">reject</span>(err);</span><br><span class="line">            <span class="title function_">resolve</span>(data);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">read</span>(A)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">read</span>(B);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">read</span>(C);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">read</span>(D);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;qianguyihao:&#x27;</span> + data);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;);</span><br></pre>

<p>这一段代码可以看出，Promise 很好的处理了回调地狱的问题。下一篇文章，我们会更详细的介绍 Promise 的链式调用。</p>
<h2 id="链式调用，如何处理-reject-失败状态"><a href="#链式调用，如何处理-reject-失败状态" class="headerlink" title="链式调用，如何处理 reject 失败状态"></a>链式调用，如何处理 reject 失败状态</h2><h3 id="例-1：不处理-reject"><a href="#例-1：不处理-reject" class="headerlink" title="例 1：不处理 reject"></a>例 1：不处理 reject</h3><pre class="highlight"><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;b.json&#x27;</span>); <span class="comment">// 继续请求 b</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// a 请求失败</span></span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;a: err&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// b 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;c.json&#x27;</span>); <span class="comment">// 继续请求 c</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// c 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;c：success&#x27;</span>);</span><br><span class="line">    &#125;);</span><br></pre>

<p>上面的代码中，假设 a 请求失败，那么，后面的代码会怎么走呢？</p>
<p>打印结果：</p>
<pre class="highlight"><span class="line">a: err</span><br><span class="line">undefined</span><br><span class="line">c：success</span><br></pre>

<p>我们可以看到，虽然 a 请求失败，但后续的请求依然会继续执行。</p>
<p>为何打印结果的第二行是 undefined？这是因为，当 a 请求走到 reject 之后，我们并没有做任何处理。这就导致，代码走到第二个 <code>then</code>的时候，<strong>其实是在执行一个空的 promise</strong>。</p>
<h3 id="例-2：单独处理-reject"><a href="#例-2：单独处理-reject" class="headerlink" title="例 2：单独处理 reject"></a>例 2：单独处理 reject</h3><pre class="highlight"><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(</span><br><span class="line">        <span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;b.json&#x27;</span>); <span class="comment">// 继续请求 b</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// a 请求失败</span></span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;a: err&#x27;</span>);</span><br><span class="line">            <span class="comment">// 【重要】即使 a 请求失败，也依然继续执行 b请求</span></span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;b.json&#x27;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// b 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;c.json&#x27;</span>); <span class="comment">// 继续请求 c</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// c 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;c：success&#x27;</span>);</span><br><span class="line">    &#125;);</span><br></pre>

<p>跟例 1 相比，例 2 在 reject 中增加了一行<code>return getPromise(&#39;b.json&#39;)</code>，意味着，即使 a 请求失败，也要继续执行 b。</p>
<p>这段代码，我们是单独处理了 a 请求失败的情况。</p>
<h3 id="统一处理-reject"><a href="#统一处理-reject" class="headerlink" title="统一处理 reject"></a>统一处理 reject</h3><p>针对 a、b、c 这三个请求，不管哪个请求失败，我都希望做统一处理。这种代码要怎么写呢?我们可以在最后面写一个 catch。</p>
<p>代码举例如下：</p>
<pre class="highlight"><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;b.json&#x27;</span>); <span class="comment">// 继续请求 b</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// b 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">getPromise</span>(<span class="string">&#x27;c.json&#x27;</span>); <span class="comment">// 继续请求 c</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// c 请求成功</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;c：success&#x27;</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">catch</span>(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 统一处理请求失败</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;);</span><br></pre>

<p>上面的代码中，由于是统一处理多个请求的异常，所以<strong>只要有一个请求失败了，就会马上走到 catch</strong>，剩下的请求就不会继续执行了。比如说：</p>
<ul>
<li><p>a 请求失败：然后会走到 catch，不执行 b 和 c</p>
</li>
<li><p>a 请求成功，b 请求失败：然后会走到 catch，不执行 c。</p>
</li>
</ul>
<h2 id="return-的返回值"><a href="#return-的返回值" class="headerlink" title="return 的返回值"></a>return 的返回值</h2><p>return 后面的返回值，有两种情况：</p>
<ul>
<li><p>情况 1：返回 Promise 实例对象。返回的该实例对象会调用下一个 then。</p>
</li>
<li><p>情况 2：返回普通值。返回的普通值会直接传递给下一个 then，通过 then 参数中函数的参数接收该值。</p>
</li>
</ul>
<p>我们针对上面这两种情况，详细解释一下。</p>
<h3 id="情况-1：返回-Promise-实例对象"><a href="#情况-1：返回-Promise-实例对象" class="headerlink" title="情况 1：返回 Promise 实例对象"></a>情况 1：返回 Promise 实例对象</h3><p>举例如下：</p>
<pre class="highlight"><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// a 请求成功。从 resolve 获取正常结果：接口请求成功后，打印a接口的返回结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="comment">// 这里的 return，返回的是 Promise 实例对象</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">resolve</span>(<span class="string">&#x27;qianguyihao&#x27;</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">    &#125;);</span><br></pre>

<h3 id="情况-2：返回-普通值"><a href="#情况-2：返回-普通值" class="headerlink" title="情况 2：返回 普通值"></a>情况 2：返回 普通值</h3><pre class="highlight"><span class="line"><span class="title function_">getPromise</span>(<span class="string">&#x27;a.json&#x27;</span>)</span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// a 请求成功。从 resolve 获取正常结果：接口请求成功后，打印a接口的返回结果</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">        <span class="comment">// 返回普通值</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;qianguyihao&#x27;</span>;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">        既然上方代码并没有返回 promise，那么，这里的 then 是谁来调用呢？</span></span><br><span class="line"><span class="comment">        答案是：这里会产生一个新的 默认的 promise实例，来调用这里的then，确保可以继续进行链式操作。</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    .<span class="title function_">then</span>(<span class="function">(<span class="params">res2</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 这里的 res2 接收的是 普通值 &#x27;qianguyihao&#x27;</span></span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(res2);</span><br><span class="line">    &#125;);</span><br></pre>

<h2 id="我的公众号"><a href="#我的公众号" class="headerlink" title="我的公众号"></a>我的公众号</h2><p>想学习<strong>更多技能</strong>？不妨关注我的微信公众号：<strong>千古壹号</strong>。</p>
<p>扫一扫，你将发现另一个全新的世界，而这将是一场美丽的意外：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="https://img.smyhvae.com/20200102.png" class="lozad post-image"src="https://img.smyhvae.com/20200102.png"></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/06-Promise%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8/">
            https://zwl5670.gitee.io/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/06-Promise%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/05-Promise%E5%85%A5%E9%97%A8%E8%AF%A6%E8%A7%A3/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">05-Promise入门详解 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2006/06/01/06-JavaScript%E5%9F%BA%E7%A1%80%EF%BC%9A%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/07-Promise%E7%9A%84%E9%9D%99%E6%80%81%E6%96%B9%E6%B3%95/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">07-Promise的静态方法 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%A4%84%E7%90%86%E5%A4%9A%E6%AC%A1-Ajax-%E8%AF%B7%E6%B1%82%E3%80%90%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">Promise 的链式调用：处理多次 Ajax 请求【重要】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#ES5-%E4%B8%AD%E7%9A%84%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">ES5 中的传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%88%9D%E6%AD%A5%E5%86%99%E6%B3%95%EF%BC%8C%E6%96%B9%E4%BE%BF%E7%90%86%E8%A7%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（初步写法，方便理解）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装一个接口）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装多个接口）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%B0%81%E8%A3%85-Node-js-%E7%9A%84%E5%9B%9E%E8%B0%83%E6%96%B9%E6%B3%95"><span class="toc-text">Promise 链式调用：封装 Node.js 的回调方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%8C%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81"><span class="toc-text">链式调用，如何处理 reject 失败状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-1%EF%BC%9A%E4%B8%8D%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 1：不处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-2%EF%BC%9A%E5%8D%95%E7%8B%AC%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 2：单独处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9F%E4%B8%80%E5%A4%84%E7%90%86-reject"><span class="toc-text">统一处理 reject</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#return-%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-text">return 的返回值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-1%EF%BC%9A%E8%BF%94%E5%9B%9E-Promise-%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1"><span class="toc-text">情况 1：返回 Promise 实例对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-2%EF%BC%9A%E8%BF%94%E5%9B%9E-%E6%99%AE%E9%80%9A%E5%80%BC"><span class="toc-text">情况 2：返回 普通值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%A4%84%E7%90%86%E5%A4%9A%E6%AC%A1-Ajax-%E8%AF%B7%E6%B1%82%E3%80%90%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">Promise 的链式调用：处理多次 Ajax 请求【重要】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#ES5-%E4%B8%AD%E7%9A%84%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">ES5 中的传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%88%9D%E6%AD%A5%E5%86%99%E6%B3%95%EF%BC%8C%E6%96%B9%E4%BE%BF%E7%90%86%E8%A7%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（初步写法，方便理解）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E4%B8%80%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装一个接口）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%88%E5%B0%81%E8%A3%85%E5%A4%9A%E4%B8%AA%E6%8E%A5%E5%8F%A3%EF%BC%89"><span class="toc-text">Promise 链式调用（封装多个接口）</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Promise-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%9A%E5%B0%81%E8%A3%85-Node-js-%E7%9A%84%E5%9B%9E%E8%B0%83%E6%96%B9%E6%B3%95"><span class="toc-text">Promise 链式调用：封装 Node.js 的回调方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F%E5%86%99%E6%B3%95"><span class="toc-text">传统写法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Promise-%E5%86%99%E6%B3%95"><span class="toc-text">Promise 写法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8%EF%BC%8C%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86-reject-%E5%A4%B1%E8%B4%A5%E7%8A%B6%E6%80%81"><span class="toc-text">链式调用，如何处理 reject 失败状态</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-1%EF%BC%9A%E4%B8%8D%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 1：不处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B-2%EF%BC%9A%E5%8D%95%E7%8B%AC%E5%A4%84%E7%90%86-reject"><span class="toc-text">例 2：单独处理 reject</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%9F%E4%B8%80%E5%A4%84%E7%90%86-reject"><span class="toc-text">统一处理 reject</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#return-%E7%9A%84%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="toc-text">return 的返回值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-1%EF%BC%9A%E8%BF%94%E5%9B%9E-Promise-%E5%AE%9E%E4%BE%8B%E5%AF%B9%E8%B1%A1"><span class="toc-text">情况 1：返回 Promise 实例对象</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%85%E5%86%B5-2%EF%BC%9A%E8%BF%94%E5%9B%9E-%E6%99%AE%E9%80%9A%E5%80%BC"><span class="toc-text">情况 2：返回 普通值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%88%91%E7%9A%84%E5%85%AC%E4%BC%97%E5%8F%B7"><span class="toc-text">我的公众号</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
